package com.xxx.datalake.utils;

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;

import java.io.IOException;

/**
 * @ Author: Aneve
 * @ Project: datalake
 * @ Since: 2022/9/21 16:35
 * @ Description:
 */
public class HBaseUtils {


    /**
     * 判断表是否存在
     *
     */
    public boolean isTableExist(String tableName, Admin admin) throws IOException {
        boolean exists = admin.tableExists(TableName.valueOf(tableName));
        return exists;
    }

    /**
     * 创建HBase表
     *
     * @param tableName      表名
     */
    public void createTable(String tableName,Admin admin,String...cfs) throws IOException {
        //1.判断是否存在列族信息
        if (cfs.length<=0) {
            System.out.println("请设置列族信息");
            return;
        }

        //2.判断表是否存在
        /*if (isTableExist(tableName,admin)){
            System.out.println(tableName+"表已存在!");
            return;
        }*/

        //3.创建表描述器
        HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));

        //4.循环添加列族信息
        for (String cf:cfs) {

            //5.创建列族描述器
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(cf);


            //6.添加具体的列族信息
            hTableDescriptor.addFamily(hColumnDescriptor);

        }

        //创建表
        admin.createTable(hTableDescriptor);
        System.out.println("表创建成功！");
    }

    /**
     * 删除HBase表
     *
     * @param tableName 表名
     */
    public void dropTable(String tableName,Admin admin) throws IOException {

        //1.判断表是否存在
        if (!isTableExist(tableName,admin)){
            System.out.println(tableName+"表不存在");
            return;
        }

        //2.使表下线
        admin.disableTable(TableName.valueOf(tableName));

        //3.删除表
        admin.deleteTable(TableName.valueOf(tableName));
    }
}
